<template>
  <div style="padding: 16px 24px">
    <a-spin
      :spinning="Object.keys(fieldConfig).length === 0"
      tip="加載表單中..."
    >
      <a-form
        ref="formRef"
        :model="formState"
        :label-col="{ span: 8, offset: 0 }"
        :wrapper-col="{ span: 15, offset: 1 }"
        :label-wrap="true"
        label-align="right"
        @finish="handleFinish"
      >
        <a-form-item
          v-for="(config, field) in fieldConfig"
          :key="field"
          :label="config.label"
          :name="field"
          :rules="config.rules"
          :extra="config.extra"
          :tooltip="config.tooltip"
        >
          <!-- 輸入框 -->
          <a-input
            v-if="config.type === 'input'"
            v-model:value="formState[field]"
            :placeholder="config.placeholder"
            autocomplete="off"
          />

          <!-- 密碼框 -->
          <a-input-password
            v-if="config.type === 'password'"
            v-model:value="formState[field]"
            :placeholder="config.placeholder"
            autocomplete="new-password"
          />

          <!-- 數字 -->
          <a-input-number
            v-if="config.type === 'number'"
            v-model:value="formState[field]"
            :placeholder="config.placeholder"
            :min="config.min"
            :max="config.max"
            :step="config.step"
            :defaultValue="0"
            style="width: 100%"
            :addonBefore="
              config.addonBefore ? addonBeforeFn(config.addonBefore) : undefined
            "
            :addonAfter="
              config.addonAfter ? addonAfterFn(config.addonAfter) : undefined
            "
          />
          <!-- 數字範圍 -->
          <div class="inline-range-input" v-if="config.type === 'numberRange'">
            <a-form-item-rest>
              <a-input-number
                v-model:value="formState[field][0]"
                :defaultValue="0"
                :min="0"
                style="width: 100%"
                :addonBefore="
                  config.addonBefore
                    ? addonBeforeFn(config.addonBefore)
                    : undefined
                "
                :addonAfter="
                  config.addonAfter
                    ? addonAfterFn(config.addonAfter)
                    : undefined
                "
              />
            </a-form-item-rest>
            <span class="separator">-</span>
            <a-input-number
              v-model:value="formState[field][1]"
              :defaultValue="0"
              :min="formState[field][0] + 1"
              style="width: 100%"
              :addonBefore="
                config.addonBefore
                  ? addonBeforeFn(config.addonBefore)
                  : undefined
              "
              :addonAfter="
                config.addonAfter ? addonAfterFn(config.addonAfter) : undefined
              "
            />
          </div>

          <!-- 日期範圍 -->
          <a-range-picker
            v-if="config.type === 'daterange'"
            v-model:value="formState[field]"
            value-format="YYYY-MM-DD"
          />
          <!-- date -->
          <a-date-picker
            v-if="config.type === 'date'"
            v-model:value="formState[field]"
            value-format="YYYY-MM-DD"
          />

          <!-- 月份選擇器 -->
          <a-date-picker
            v-model:value="formState[field]"
            v-else-if="config.type === 'date-picker'"
            :placeholder="config.placeholder"
            :picker="config.picker"
            :valueFormat="getValueFormat(config.picker)"
          />

          <!-- 單選-->
          <a-radio-group
            v-model:value="formState[field]"
            v-if="config.type === 'radio'"
            :disabled="config.disabled"
          >
            <a-radio
              v-for="option in config.options"
              :key="option.key"
              :value="option.key"
            >
              {{ option.label }}
            </a-radio>
          </a-radio-group>
          <!-- 多選-->
          <a-checkbox-group
            v-if="config.type === 'checkbox'"
            v-model:value="formState[field]"
          >
            <a-checkbox
              v-for="option in config.options"
              :key="option.key"
              :value="option.key"
            >
              {{ option.label }}
            </a-checkbox>
          </a-checkbox-group>
          <!-- 開關-->
          <a-switch
            v-if="config.type === 'switch'"
            v-model:checked="formState[field]"
          >
            <template #checkedChildren><check-outlined /></template>
            <template #unCheckedChildren><close-outlined /></template>
          </a-switch>
          <!-- 下拉選擇 -->
          <a-select
            v-if="config.type === 'select'"
            show-search
            v-model:value="formState[field]"
            :placeholder="config.placeholder"
            :mode="config.mode"
            :disabled="disabledFn(config.disabled)"
          >
            <a-select-option
              v-for="option in config.options"
              :key="option.key"
              :value="option.key"
              :disabled="option.disabled || false"
            >
              {{ option.label }}
            </a-select-option>
          </a-select>

          <!-- 遠程數據選項框 -->
          <a-select
            v-if="config.type === 'remoteSelect'"
            v-model:value="formState[field]"
            show-search
            :mode="config.mode"
            :placeholder="config.placeholder"
            :filter-option="false"
            :options="config.options"
            :not-found-content="searching ? undefined : null"
            @search="(value: string) => getOptions(value, config)"
            @change="(value: string, option) => {
              // 選中後調用
              // console.log('value', value)
              // console.log('option', option)
            }"
          >
            <template v-if="searching" #notFoundContent>
              <a-spin size="small" />
            </template>
          </a-select>

          <!-- checkbox -->
          <a-checkbox-group
            v-if="config.type === 'checkboxGroup'"
            v-model:value="formState[field]"
            style="width: 100%"
          >
            <a-checkbox
              v-for="option in config.options"
              :key="option.key"
              :value="option.key"
            >
              {{ option.label }}
            </a-checkbox>
          </a-checkbox-group>

          <!-- end -->
        </a-form-item>

        <a-flex justify="flex-end">
          <a-button type="primary" html-type="submit" :loading="submitting"
            >提交</a-button
          >
          <a-button style="margin-left: 10px" @click="resetForm">重置</a-button>
        </a-flex>
      </a-form>
    </a-spin>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from "vue";
import { FormInstance } from "ant-design-vue";
import type { FormFieldConfig } from "@/types/form";
import { CheckOutlined, CloseOutlined } from "@ant-design/icons-vue";

interface Props {
  fieldConfig: Record<string, FormFieldConfig>;
  formData?: any;
  type?: "general" | "create" | "edit";
}

const props = defineProps<Props>();
const formRef = ref<FormInstance>();

// 統一表單狀態管理
const formState = reactive<Record<string, any>>({});

// 初始化表單的核心邏輯函數（合併默認值 + 外部數據）
const initializeFormState = (
  fieldConfig: Record<string, FormFieldConfig>,
  formData?: Record<string, any>
): Record<string, any> => {
  return Object.fromEntries(
    Object.keys(fieldConfig).map((field) => {
      const config = fieldConfig[field];
      const externalValue = formData?.[field];
      // 優先使用外部傳入的數據，其次使用配置的默認值
      if (config.type === "numberRange") {
        return [field, externalValue || [0, 0]]; // 空值保護
      }
      // 值優先級：外部數據 > 默認值 > undefined
      return [field, externalValue ?? config.defaultValue ?? undefined];
    })
  );
};

// 監聽配置和數據變化
watch(
  () => [props.fieldConfig, props.formData],
  ([newConfig, newData]) => {
    const newState = initializeFormState(newConfig, newData);

    // 智能合併狀態，保留用戶已輸入內容
    Object.entries(newState).forEach(([key, value]) => {
      if (!Object.is(formState[key], value)) {
        formState[key] = value;
      }
    });
  },
  { immediate: true, deep: true }
);

const addonBeforeFn = (addonBefore: any) => {
  if (typeof addonBefore === "function") {
    return addonBefore(formState);
  } else {
    return addonBefore;
  }
};
const addonAfterFn = (addonAfter: any) => {
  if (typeof addonAfter === "function") {
    return addonAfter(formState);
  } else {
    return addonAfter;
  }
};

const disabledFn = (disabled: any) => {
  if (typeof disabled === "function") {
    return disabled(props.type);
  } else {
    return disabled;
  }
};

const searching = ref(false);
const getOptions = async (value: string, config: any) => {
  config.options = [];
  searching.value = true;
  try {
    config.options = await config.searchFn(value);
  } catch (error) {
    console.error("獲取選項失敗", error);
  } finally {
    searching.value = false;
  }
};

const getValueFormat = (picker: string) => {
  switch (picker) {
    case "year":
      return "YYYY";
    case "month":
      return "YYYY-MM";
    case "quarter":
      return "YYYY-[Q]Q";
    case "week":
      return "YYYY-[W]WW";
    case "date":
      return "YYYY-MM-DD";
    default:
      return "YYYY-MM-DD";
  }
};

const emit = defineEmits(["submit"]);

const submitting = ref(false);
const handleFinish = (data: any) => {
  submitting.value = true;
  emit("submit", data);
};

const resetLoading = () => {
  submitting.value = false;
};

const resetForm = () => {
  formRef.value?.resetFields();
};

// 暴露 resetForm 方法
defineExpose({
  resetForm,
  resetLoading,
});
</script>

<style scoped>
.inline-range-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

.separator {
  color: #999;
  padding: 0 8px;
}
</style>
